<?php
// ----------------------------------------------------------
// * @Copyright @ 2011-2020 By HuaXiaXinCai
// ----------------------------------------------------------
// * @Author Yang Changwu<800334@qq.com> 2016-12-12
// ----------------------------------------------------------
namespace Controller;
use \GatewayWorker\Lib\Gateway;
use \Controller\Core;

class Login extends Core{

    public function Login($data, $client_id) {
        //处理用户增加前辍问题
        //$user = explode('_', $data['username']);
        //$username = empty($user[1]) ? $user[0]:$user[1];
        
        //签名校验
        $sign = $this->genSign($data, $this->config['loginkey']);
        //md5("username=".$data['username']."&gid=2&sid=1&time=".$data['time']."&ip=".$data['ip']."&channel=".$this->config['channel']."&key=".$this->config['loginkey']);
        if($sign != $data['sign']){
            //本地测试注释掉
            //return self::SendMsg(1004,array('method'=>'Login','id'=>md5($user['client_id'])));
        }
        
        $user = $this->db->select('*')->from('sz_user')->where("username='".$data['username']."'")->row();
        //判断用户是否禁止登录
        if($user['status'] == 1){
            $msg = [
                'method' => 'Login',
                'username' => $data['username'],
            ];
            return self::SendMsg(1010,$msg);
        }
        //检查用户是否存在
        if($user){
            if($data['id']){
                //禁止多窗口登录
                if(md5($user['client_id']) == $data['id']){
                    //通知客户端离线
                    self::SendMsg(1012,array('method'=>'Closed','id'=>$user['client_id']),2,$user['client_id']);
                    //断开客户端
                    Gateway::closeClient($user['client_id']);
                }else{
                    return self::SendMsg(1004,array('method'=>'Login','id'=>md5($user['client_id'])));
                }
            }else{
                //判断用户在线状态
                if(Gateway::isUidOnline($user['username']) == 1){
                    $msg = [
                        'method'    => 'Login',
                        'username'  => $data['username'],
                        'id'        => md5($user['client_id']),
                        'sign'      => md5($user['client_id']),
                    ];
                    return self::SendMsg(1011,$msg);
                }
            }
           //存在更新
           $arr = [
                'lasttime'  => time(),
                'lastip'    => $_SERVER['REMOTE_ADDR'],
                'online'    => 1,
                'client_id' => $client_id,
            ];
            $this->db->update('sz_user')->cols($arr)->where("username='".$data['username']."'")->query();
        }else{
            //检查昵称
            $nickname = $this->db->select('nickname')->from('sz_user')->where("nickname='".$data['nickname']."'")->row();
            if($nickname){
               $msg = [
                    'method'    => 'Login',
                    'username'  => $data['username'],
               ];
               return self::SendMsg(1009,$msg);
            }
            //不存在插入
            $user = [
                'username'  => $data['username'],
                'nickname'  => $data['nickname'],
                'sex'       => $data['sex'],
                'avatar'    => $data['avatar'],
                'channel'   => $data['channel'],
                'gold'      => 0,
                'money'     => 0,
                'logintime' => time(),
                'lasttime'  => time(),
                'loginip'   => $_SERVER['REMOTE_ADDR'],
                'lastip'    => $_SERVER['REMOTE_ADDR'],
                'roulette'  => 1,
                'dateline'  => 0,
                'dayline'  => 0,
                'online'    => 1,
                'client_id' => $client_id,
            ];
            $ret=$this->db->insert('sz_user')->cols($user)->query();
            $user['uid'] = $ret;
        }
        //登录记录
        $log['channel'] = $user['channel'];
        $log['username'] = $user['username'];
        $log['gameid'] = 2;
        $log['serverid'] = 1;
        $log['logintime'] = time();
        $log['loginip'] = $_SERVER['REMOTE_ADDR'];
        $log['remark'] = '';
        $this->db->insert('sz_login_log')->cols($log)->query();
        
        // 设置session
        $_SESSION = [
            'username'          => $user['username'],
            'uid'               => $user['uid'],
            'gold'              => $user['gold'],
            'money'             => $user['money'],
            'dateline'      	=> $user['dateline'],
            'logintime' 	=> $user['logintime'],
            'dayline'           => $user['dayline'],
            'roulette'          => $user['roulette'],
            'lasttime'          => $user['lasttime'],
            'client_id'         => $client_id,
        ];

        // 将当前链接与username绑定
        Gateway::bindUid($client_id, $user['username']);
        
        //用户定时器
        self::UserTimer($user['username']);
        
        // 通知当前客户端初始化
        $msg = [
            'method' 	=> 'Login',
            'username' 	=> $user['username'],
            'nickname' 	=> $user['nickname'],
            'sex' 	=> $user['sex'],
            'gold'	=> $user['gold'],
            'money'	=> $user['money'],
            'avatar'	=> $user['avatar'],
            'id'	=> md5($client_id),
            'sign'	=> md5($client_id),
        ];
        self::SendMsg(1001,$msg);
    }
    //检测用户名
    public function CheckUsername($data,$client_id){
        $user = $this->db->select('*')->from('sz_user')->where("username='".$data['username']."'")->row();
        if($user){
            $msg = [
                'method' => 'CheckUsername',
                'username' => $data['username'],
            ];
            return self::SendMsg(1008,$msg);
        }else{
            $msg = [
                'method' => 'CheckUsername',
                'username' => $data['username'],
            ];
            return self::SendMsg(1001,$msg);
        }
    }
    //检查昵称
    public function CheckNickname($data,$client_id){
        $user = $this->db->select('*')->from('sz_user')->where("nickname='".$data['nickname']."'")->row();
        if($user){
            $msg = [
                'method' => 'CheckNickname',
                'username' => $data['username'],
            ];
            return self::SendMsg(1009,$msg);
        }else{
            $msg = [
                'method' => 'CheckNickname',
                'username' => $data['username'],
            ];
            return self::SendMsg(1001,$msg);
        }
    }

    //签名
    public function genSign($data, $secret_key)
    {
        $query_arr = array();
        $query_str = '';
        ksort($data);
        foreach ($data as $key => $val) {
            if ($key == "sign") {
                continue;
            }
            array_push($query_arr, $key . '=' . $val);
        }

        $query_str = implode('&', $query_arr);
        return md5($query_str. '&' . $secret_key);
    }
}